package com.sskj.ws.task;

import com.sskj.ws.factory.DeviceSubscriptionFactory;
import com.sskj.ws.server.WebSocketServer;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Iterator;

@Slf4j
@Component
public class WebSocketSessionTask {

    @Autowired
    private DeviceSubscriptionFactory deviceSubscriptionFactory;

    @Scheduled(fixedRate = 30000)
    public void cleanInvalidSession() {
        long start = System.currentTimeMillis();
        int removed = 0;

        Iterator<WebSocketServer> iterator = WebSocketServer.getWebSocketServers().iterator();
        while (iterator.hasNext()) {
            WebSocketServer next = iterator.next();
            Session session = next.getSession();

            if (session == null || !session.isOpen()) {
                iterator.remove();
                deviceSubscriptionFactory.clearSession(session);
                removed++;
            }
        }

        if (removed > 0) {
            log.info("[WS会话连接清理任务]-清理了 {} 个无效 WebSocket 连接，耗时 {}ms", removed, System.currentTimeMillis() - start);
        }
    }
}
